package cn.com.eado.crm.app.extenstion

import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.NavHostFragment
import cn.com.eado.crm.R
import cn.com.eado.crm.app.MyApp

/**
 * 扩展toast
 */
fun Context.toast(msg: String?, duration: Int = Toast.LENGTH_SHORT){
    val toast:Toast = Toast.makeText(MyApp.instance, msg+"", duration)
    toast.setGravity(Gravity.CENTER, 0,0)  //居中
//    toast.view.setBackgroundResource(R.drawable.shape_gray_round_corner)  //背景
    val layout: LinearLayout = toast.view as LinearLayout
    val textView: TextView = layout.getChildAt(0) as TextView
    textView.setTextColor(Color.WHITE)  //文字颜色
//    textView.setPadding(3,0,3,0)
    toast.show()
}

/**
 * 获取activity中指定的fragment类型（判断当前是否是该fragment）
 */
@Suppress("UNCHECKED_CAST")
fun <F : Fragment> AppCompatActivity.getFragment(fragmentClass: Class<F>): F? {
    val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment

    navHostFragment.childFragmentManager.fragments.forEach {
        if (fragmentClass.isAssignableFrom(it.javaClass)) {
            return it as F
        }
    }

    return null
}

/**
 * 和上面的差不多
 */
fun AppCompatActivity.getCurrentFragment(): Fragment? {
    val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment
    navHostFragment.childFragmentManager.fragments.forEach {
        return it
    }

    return null
}